package cp4.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/cp4/cookie/set")
public class SetCookiePropertyServlet extends HttpServlet {
    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String value = df.format(new Date());
        System.out.println(value);
        Cookie c= new Cookie("last_visit", "value");
        // 设置cookie的有效期，如果不设置则表示该cookie时会话cookie，表示浏览器一旦关闭则该cookie就失效了，单位为秒
        c.setMaxAge(60 * 60 * 24 * 365); // 设置1年有效期
        c.setPath("/");// 设置cookie为根目录，如果不设置则默认为该servlet路径的目录
        c.setHttpOnly(true); // 设置是否只允许服务器读取，而不允许客户端js读取

        c.setSecure(true); // 设置是否安全
        c.setComment("this is a test cookie"); // 设置cookie的注释
        resp.addCookie(c); // 不要忘记添加到resp中
        resp.getWriter().println("cookie set");
    }
}
